package com.example.springbootpro;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

@SpringBootApplication
public class SpringBootProApplication implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(SpringBootProApplication.class);


    @Value("${server.port}")
    private String port;

    @Value("${springdoc.swagger-ui.path:/swagger-ui.html}")
    private String swaggerPath;

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    private final Environment environment;

    public SpringBootProApplication(Environment environment) {
        this.environment = environment;
    }


    public static void main(String[] args) {
         SpringApplication.run(SpringBootProApplication.class, args);
    }


    @PostConstruct
    public void printSwaggerUrl() {
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            String hostName = InetAddress.getLocalHost().getHostName();

            // 获取应用上下文路径（如果有）
            String actualContextPath = contextPath.startsWith("/") ? contextPath : "/" + contextPath;

            // 构建完整的Swagger访问URL
            String swaggerUrl = String.format("http://%s:%s%s%s", ip, port, actualContextPath, swaggerPath);
            String knife4jUrl = String.format("http://%s:%s%s/doc.html", ip, port, actualContextPath);

            // 获取当前环境
            String env = String.join(",", environment.getActiveProfiles());
            if (env.isEmpty()) {
                env = "default";
            }

            // 打印日志信息
            System.out.println("\n----------------------------------------------------------");
            System.out.println("Application is running! Access URLs:");
            System.out.printf("Local: \t\thttp://localhost:%s%s\n", port, actualContextPath);
            System.out.printf("External: \thttp://%s:%s%s\n", hostName, port, actualContextPath);
            System.out.printf("Swagger UI: \t%s\n", swaggerUrl);
            System.out.printf("Knife4j UI: \t%s\n", knife4jUrl);
            System.out.printf("Profiles: \t%s\n", env);
            System.out.println("----------------------------------------------------------\n");

        } catch (UnknownHostException e) {
            System.err.println("Could not determine IP address: " + e.getMessage());
        }
    }

    @Autowired
    @Qualifier("oracleJdbcTemplate")
    private JdbcTemplate oracleJdbcTemplate;

    @Autowired
    @Qualifier("mysqlJdbcTemplate")
    private JdbcTemplate mysqlJdbcTemplate;

    @Autowired
    @Qualifier(value = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;


    @Value("${spring.profiles.active}")
    private  String ev;
    @Override
    public void run(ApplicationArguments args) throws Exception {
 if (ev.equals("prod"))
 {

//     testMySQLConnection();
//     testRedisConnection();
//     testOracleConnection();
 }
    }

    private void testOracleConnection() {
        try {
            oracleJdbcTemplate.queryForObject("SELECT 1 FROM DUAL", Integer.class);
            logger.info("================================>>>>>>");
            logger.info(".....................Oracle database connection test successful..................");
        } catch (Exception e) {
            logger.error("Oracle database connection test failed", e);
        }
    }

    private void testMySQLConnection() {
        try {
            mysqlJdbcTemplate.queryForObject("SELECT 1", Integer.class);
            logger.info("================================>>>>>>");
            logger.info("MySQL database connection test successful");
        } catch (Exception e) {
            logger.error("MySQL database connection test failed", e);
        }
    }

    private void testRedisConnection() {
        try {
            logger.info("================================>>>>>>");
            redisTemplate.opsForValue().set("test","redis数据库连接成功！！！！");
            System.out.println(redisTemplate.opsForValue().get("test"));
            logger.info("Redis connection test successful");
        } catch (Exception e) {
            logger.error("Redis connection test failed", e);
        }
    }
}